import React, { useRef } from "react";
import { message, Collapse } from "antd";

import {
  EnvironmentOutlined,
  RightOutlined,
} from "@ant-design/icons";


import { FCForm } from "@components";
import useGetFields from "../config/searchConfig";
import styles from "../styles/search.module.css";

const { Panel } = Collapse;

const Search = React.memo(({list, submit}) => {

  const onFinish = (values) => {
    let empty = Object.values(values).some(item => item)
    if (!empty) {
      message.info('查询条件不能为空')
      return
    }
    submit(values)
  };

  const toggleBtnFunc = (e) => {
    const classList = e.target.classList;
    const classNameLength = e.target.classList.length;
    const parentNode = e.target.parentNode;
    if (classNameLength === 1) {
      classList.add(styles.toggle_btn_open)
      parentNode.style.left = '0px'
    } else {
      classList.remove(styles.toggle_btn_open)
      parentNode.style.left = '-460px'
    }
  };

  const setMapCenter = (item) => {
    const { longitude, latitude } = item;
    if (!longitude || !latitude) {
      message.error("非常抱歉，该地址的经纬度有误");
    }
    React.Map.setCenter(new BMapGL.Point(longitude, latitude));
  };

  const formRef = useRef("queryFormRef");
  const formProps = {
    name: "mapSearch",
    formRef: formRef,
    fields: useGetFields(formRef),
    layoutProps: {
      layout: "grid",
      gridConfig: { colCount: 2 },
    },
    submitButton: { show: true },
    resetButton: { show: true },
    onFinish,
    isButtonLineFeed: false,
  };

  return (
    <div className={styles.search}>
      <FCForm {...formProps}/>
      <button type="button" className={`${styles.toggle_btn} ${styles.toggle_btn_open}`} onClick={toggleBtnFunc} />
      <Collapse accordion className={styles.address_box} expandIconPosition='end'>
        <Panel header="风险地址列表" key="1">
          <ul className={styles.list}>
            {list.map((item) => {
              return (
                <li key={item.latitude} onClick={() => setMapCenter(item)}>
                  <EnvironmentOutlined />
                  <span className={styles.areaName}>{item.policyHolder || item.areaName || item.address}</span>
                  <RightOutlined />
                </li>
              );
            })}
          </ul>
        </Panel>
      </Collapse>
    </div>
  );
});

export default Search;
